<template>
  <el-dialog
    :model-value="visible"
    width="580px"
    title="获取密码"
    @close="handleClose"
    :fullscreen="mobile"
    :destroy-on-close="true"
    class="pwd-dialog"
  >
    <el-form :model="form" label-width="100px" ref="formRef" :rules="rules">
      <el-form-item label="密码类型" prop="pwdMode">
        <el-radio-group v-model="form.pwdMode" @change="handlePwdModeChange" size="large">
          <el-radio-button :label="1">随机密码</el-radio-button>
          <el-radio-button :label="2">自定义密码</el-radio-button>
        </el-radio-group>
      </el-form-item>
      
      <!-- 随机密码选项 -->
      <template v-if="form.pwdMode === 1">
        <el-form-item label="密码名称" prop="keyboardPwdName">
          <el-input v-model="form.keyboardPwdName" placeholder="请输入密码名称" />
        </el-form-item>
        
        <el-form-item label="密码类型" prop="keyboardPwdType">
          <el-select v-model="form.keyboardPwdType" placeholder="请选择密码类型" @change="handlePwdTypeChange" style="width: 100%">
            <el-option label="单次密码" :value="1">
              <div class="pwd-type-option">
                <span>单次密码</span>
                <span class="pwd-type-desc">只能在开始时间后6小时内使用一次</span>
              </div>
            </el-option>
            <el-option label="永久密码" :value="2">
              <div class="pwd-type-option">
                <span>永久密码</span>
                <span class="pwd-type-desc">从开始时间开始永久有效，必需在开始时间24小时内使用一次</span>
              </div>
            </el-option>
            <el-option label="期限密码" :value="3">
              <div class="pwd-type-option">
                <span>期限密码</span>
                <span class="pwd-type-desc">在开始和结束时间内有效，必需在开始时间24小时内使用一次</span>
              </div>
            </el-option>
            <el-option label="清空码" :value="4">
              <div class="pwd-type-option">
                <span>清空码</span>
                <span class="pwd-type-desc">在锁上使用后会删除之前在锁上使用过的密码</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <!-- 仅期限密码需要显示有效期 -->
        <el-form-item label="有效期" prop="date" v-if="form.keyboardPwdType === 3">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateChange"
            style="width: 100%"
          />
        </el-form-item>
      </template>
      
      <!-- 自定义密码选项 -->
      <template v-if="form.pwdMode === 2">
        <el-form-item label="密码名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入密码名称" />
        </el-form-item>
        
        <el-form-item label="密码" prop="keyboardPwd">
          <el-input v-model="form.keyboardPwd" placeholder="请输入4-9位数字密码" maxlength="9" show-password />
        </el-form-item>
        
        <el-form-item label="密码类型" prop="customPwdType">
          <el-radio-group v-model="form.customPwdType" @change="handleCustomTypeChange">
            <el-radio :label="1">限时</el-radio>
            <el-radio :label="2">永久</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 仅限时密码需要显示有效期 -->
        <el-form-item label="有效期" prop="date" v-if="form.customPwdType === 1">
          <el-date-picker
            v-model="customDateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleCustomDateChange"
            style="width: 100%"
          />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleOk" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup name="GetPwdDl">
import useAppStore from '@/store/modules/app'
import { getCurrentInstance, watch } from 'vue'
import LockApi from "@/api/device/lock.js";

const { proxy } = getCurrentInstance()

const emit = defineEmits(['ok', 'cancel', 'refresh'])
const props = defineProps({
  visible: Boolean,
  lockId: String
})

const loading = ref(false)
const dateRange = ref([])
const customDateRange = ref([])
const mobile = computed(() => useAppStore().device === 'mobile')

const form = reactive({
  pwdMode: 1, // 1-随机密码，2-自定义密码
  keyboardPwdType: 1, // 1-单次，2-永久，3-期限，4-清空码
  customPwdType: 1, // 1-限时，2-永久
  keyboardPwd: '', // 自定义密码
  keyboardPwdName: '', // 随机密码名称
  name: '', // 自定义密码名称
  startDate: '',
  endDate: '',
  customStartDate: '',
  customEndDate: ''
})

const rules = reactive({
  keyboardPwdType: [{ required: true, message: '请选择密码类型', trigger: 'change' }],
  keyboardPwdName: [{ required: true, message: '请输入密码名称', trigger: 'blur' }],
  name: [{ required: true, message: '请输入密码名称', trigger: 'blur' }],
  keyboardPwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^\d{4,9}$/, message: '请输入4-9位数字密码', trigger: 'blur' }
  ],
  startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
})

// 监听对话框显示状态
watch(() => props.visible, (val) => {
  if (val) {
    // 对话框打开时初始化表单
    initForm()
  }
})

// 初始化表单
function initForm() {
  form.pwdMode = 1
  form.keyboardPwdType = 1
  form.customPwdType = 1
  form.keyboardPwd = ''
  form.keyboardPwdName = ''
  form.name = ''
  form.startDate = ''
  form.endDate = ''
  form.customStartDate = ''
  form.customEndDate = ''
  
  // 设置默认时间范围
  setDefaultTimeRange()
}

// 设置默认时间范围
function setDefaultTimeRange() {
  const now = new Date()
  const twoHoursLater = new Date(now.getTime() + 2 * 60 * 60 * 1000) // 当前时间加2小时
  
  // 格式化时间
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  const nowFormatted = formatDate(now)
  const laterFormatted = formatDate(twoHoursLater)
  
  // 设置随机密码的时间范围
  form.startDate = nowFormatted
  form.endDate = laterFormatted
  dateRange.value = [nowFormatted, laterFormatted]
  
  // 设置自定义密码的时间范围
  form.customStartDate = nowFormatted
  form.customEndDate = laterFormatted
  customDateRange.value = [nowFormatted, laterFormatted]
}

// 处理密码模式变化
function handlePwdModeChange() {
  // 重置相关字段
  if (form.pwdMode === 1) {
    form.keyboardPwd = ''
    form.name = ''
  } else {
    form.keyboardPwdName = ''
  }
}

// 处理随机密码类型变化
function handlePwdTypeChange(value) {
  if (value === 2) { // 永久密码
    form.startDate = new Date().toISOString().slice(0, 19).replace('T', ' ')
    form.endDate = '2099-12-31 00:00:00'
    dateRange.value = [form.startDate, form.endDate]
  } else if (value === 1 || value === 4) { // 单次密码或清空码
    form.startDate = new Date().toISOString().slice(0, 19).replace('T', ' ')
    form.endDate = ''
    dateRange.value = []
  } else { // 期限密码
    setDefaultTimeRange()
  }
}

// 处理自定义密码类型变化
function handleCustomTypeChange(value) {
  if (value === 2) { // 永久
    form.customStartDate = new Date().toISOString().slice(0, 19).replace('T', ' ')
    form.customEndDate = '2099-12-31 00:00:00'
    customDateRange.value = [form.customStartDate, form.customEndDate]
  } else { // 限时
    setDefaultTimeRange()
  }
}

// 处理随机密码日期变化
function handleDateChange(val) {
  if (val) {
    form.startDate = val[0]
    form.endDate = val[1]
  } else {
    form.startDate = ''
    form.endDate = ''
  }
}

// 处理自定义密码日期变化
function handleCustomDateChange(val) {
  if (val) {
    form.customStartDate = val[0]
    form.customEndDate = val[1]
  } else {
    form.customStartDate = ''
    form.customEndDate = ''
  }
}

function handleClose() {
  emit('cancel')
}

function handleOk() {
  proxy.$refs['formRef'].validate(valid => {
    if (valid) {
      loading.value = true
      
      if (form.pwdMode === 1) {
        // 随机密码
        getRandomPassword()
      } else {
        // 自定义密码
        setCustomPassword()
      }
    }
  })
}

// 获取随机密码
function getRandomPassword() {
  // 验证期限密码必须有结束时间
  if (form.keyboardPwdType === 3 && !form.endDate) {
    proxy.$modal.msgError('请选择有效期')
    loading.value = false
    return
  }
  
  const params = {
    keyboardPwdType: form.keyboardPwdType,
    startDate: form.startDate,
    keyboardPwdName: form.keyboardPwdName // 添加密码名称
  }
  
  // 只有期限密码需要结束时间
  if (form.keyboardPwdType === 3) {
    params.endDate = form.endDate
  }
  
  LockApi.getRandomPwd(props.lockId, params).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess('获取密码成功')
      emit('ok', res.data)
      emit('refresh') // 添加刷新事件
    } else {
      proxy.$modal.msgError(res.msg || '获取密码失败')
    }
  }).catch(err => {
    console.error(err)
    proxy.$modal.msgError('获取密码失败')
  }).finally(() => {
    loading.value = false
  })
}

// 设置自定义密码
function setCustomPassword() {
  // 验证限时密码必须有结束时间
  if (form.customPwdType === 1 && !form.customEndDate) {
    proxy.$modal.msgError('请选择有效期')
    loading.value = false
    return
  }
  
  const params = {
    lockId: props.lockId,
    keyboardPwd: form.keyboardPwd,
    startDate: form.customStartDate,
    name: form.name // 添加密码名称
  }
  
  // 只有限时密码需要结束时间
  if (form.customPwdType === 1) {
    params.endDate = form.customEndDate
  } else {
    params.endDate = '2099-12-31 00:00:00'
  }
  
  LockApi.addPwd(params).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess('设置密码成功')
      emit('ok', params)
      emit('refresh') // 添加刷新事件
    } else {
      proxy.$modal.msgError(res.msg || '设置密码失败')
    }
  }).catch(err => {
    console.error(err)
    proxy.$modal.msgError('设置密码失败')
  }).finally(() => {
    loading.value = false
  })
}

// 初始化
initForm()
</script>

<style scoped>
.pwd-dialog :deep(.el-dialog__body) {
  padding-top: 10px;
}

.pwd-type-option {
  display: flex;
  flex-direction: column;
}

.pwd-type-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 3px;
}
</style>
